package com.ybg.engine.task;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.ybg.util.DateTimeUtil;
import com.ybg.util.LogUtil;
 /**
  * 老师发起点名半个小时后结束点名调度任务
 * @author huang nc
 * @since  2017年4月26日
 */
public class UpdateDmztStatusTask extends Task{

	private static boolean running = false;
    public List<Map<String,Object>> exportData = new ArrayList<Map<String,Object>>();
    public LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
    
	@Override
	public void run() throws Exception {
	 if (!enter()){
            throw new RuntimeException("调度已经在进行中");
        }
        LogUtil.warn("teacher-course-stati...begin........");
        long begin = new Date().getTime();

        System.out.println("你看到我了吗？");
        UpdateDmztStatus();
        //TaskUtil.markProcess(jdbcTemplate, TaskName.UPDATE_STATUS, DateTimeUtil.getToday(DateTimeUtil.YYYY_MM_DD_HH_MM_SS));
        long end = new Date().getTime();
        LogUtil.info("本次任务用时 :" + (end - begin) / 1000 + "秒");
        LogUtil.warn("teacher-course-stati...begin........");
        leaving();
	}

	//发起点名半个小时后，结束点名。
	private void UpdateDmztStatus() {
		String updateStatusSql = "update ybg_b_sign set dmzt = 1 where dmzt = 0 and dmid = ? and dmsj = ?　";
		String dmsjSql = "select dmid,dmsj from YBG_B_SIGN GROUP BY dmid,dmsj";
		
		List<Map<String, Object>> lisMaps = new ArrayList<Map<String,Object>>();
		SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        long now = System.currentTimeMillis();
        String nowStr = format.format(now).substring(11, 19);
        long nowTime = 0 ;
        long dmsj = 0;
        try {
		    	lisMaps = jdbcTemplate.queryForList(dmsjSql);
				nowTime  = DateTimeUtil.HH_MM_SS2.parse(nowStr).getTime();
			for (Map<String, Object> map : lisMaps) {
				String newDmsj = (String) map.get("dmsj");
				String newDmsj2 = newDmsj.substring(11, 19);
				dmsj = DateTimeUtil.HH_MM_SS2.parse(newDmsj2).getTime();
				long time = (nowTime - dmsj)/(1000*60*60);
				if (time>30) {
					jdbcTemplate.update(updateStatusSql, map.get("dmid"),map.get("dmsj"));
				}
			}
        } catch (Exception e) {
			e.printStackTrace();
		}
	}

	private synchronized boolean enter(){
        if(running){
            return false;
        }else{
            running = true;
            return true;
        }
    }

    private synchronized void leaving(){
        running = false;
    }

	@Override
	public String setSuccessResultMsg() {
		return "结束老师点名调度成功";
	}

}
